package com.czk.random;

import com.czk.ServerIps;

import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/4/22 14:55
 */
public class WeightRandom {
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            System.out.println("拿到的服务器" + getServer_1());
        }
    }

    public static String getServer() {
        int totalWeight = 0;
        for (Integer value : ServerIps.WEIGHT_LIST.values()) {
            totalWeight += value;
        }
        // 创建随机对象
        Random random = new Random();
        // 拿到随机数
        int pos = random.nextInt(totalWeight);
        // 遍历list
        for (String ip : ServerIps.WEIGHT_LIST.keySet()) {
            // 拿到权值
            Integer weight = ServerIps.WEIGHT_LIST.get(ip);
            // 比较
            if (pos < weight) {
                return ip;
            }
            // 减去上一个的权值
            pos = pos - weight;
        }
        return "";
    }

    /**
     * 带权值的随机轮询算法的实现
     *
     * @return
     */
    public static String getServer_1() {
        // 拿到所有权值和
        int totalWeight = 0;
        for (Integer value : ServerIps.WEIGHT_LIST.values()) {
            totalWeight += value;
        }
        // 拿到随机值
        int i = ThreadLocalRandom.current().nextInt(totalWeight);
        // 遍历
        for (String ip : ServerIps.WEIGHT_LIST.keySet()) {
            // 拿到权值
            Integer weight = ServerIps.WEIGHT_LIST.get(ip);
            if (i < weight) {
                return ip;
            }
            i = i - weight;
        }
        return "";
    }
}
